<template>
  <el-upload
    ref="RefUploadFile"
    action="#"
    :drag="drag"
    :accept="accept"
    :multiple="isMultiple"
    :limit="limit"
    :show-file-list="showFileList"
    :file-list="fileList"
    :disabled="disabled"
    :before-upload="beforeUpload"
    :http-request="handleUpload"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :on-exceed="handleExceed"
    :on-success="handleSuccess"
  >
    <el-button size="small" type="primary" v-if="isBtnIcon">
      {{ btnText }}
    </el-button>

    <el-button size="small" type="text" v-else-if="isBtnText">
      {{ btnText }}
    </el-button>

    <template v-else>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    </template>

    <div v-if="hasTip" slot="tip" class="el-upload__tip">
      {{ tipContent }}
    </div>

    <!-- 预览 -->
    <!-- <z-preview :visible.sync="dialogPreview" :data="previewFile"></z-preview> -->
  </el-upload>
</template>

<script>
import {
  attachmentTypeList,
  limitImageType,
  limitExcelType,
  limitWordType,
  limitPackageType
} from '@/libs/dict/attachement-dict';
import { uploadApi } from '@/api/upload-api';

export default {
  name: 'UploadFile',
  props: {
    btnText: {
      type: String,
      default: '点击上传'
    },
    drag: {
      type: Boolean,
      default: true
    },
    isBtnText: {
      type: Boolean,
      default: false
    },
    isBtnIcon: {
      type: Boolean,
      default: false
    },
    limitText: {
      type: String,
      default: ''
    },
    limit: {
      type: Number,
      default: 10
    },
    isMultiple: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: () => []
    },
    maxSize: {
      type: Number,
      default: 20
    },
    hasTip: {
      type: Boolean,
      default: true
    },

    accept: {
      type: String,
      default() {
        return attachmentTypeList.join(',');
      }
    },
    showFileList: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isUpload: false,
      loading: false,
      dialogPreview: false,
      previewFile: {},
      limitImageType,
      limitExcelType,
      limitWordType,
      limitPackageType,
      fileType: ''
    };
  },
  computed: {
    tipContent() {
      return `上传类型:${this.accept},大小不能超过${this.maxSize}M`;
    },
    isImage() {
      return this.limitImageType.includes(this.fileType);
    },
    isExcel() {
      return this.limitExcelType.includes(this.fileType);
    },
    isWord() {
      return this.limitWordType.includes(this.fileType);
    },
    isPdf() {
      return this.fileType === 'pdf';
    },
    isPackage() {
      return this.limitPackageType.includes(this.fileType);
    }
  },
  beforeDestroy() {
    this.fileType = '';
  },
  methods: {
    // 自定义上传
    async handleUpload(option) {
      this.loading = true;
      const formData = new FormData();
      formData.append('file', option.file);
      try {
        const { code, data } = await uploadApi(formData);
        if (code === 200) {
          this.fileList.push(data);
          this.$emit('send-file-list', this.fileList);

          return data; // 返回包含上传成功数据的Promise对象
        }
      } catch (err) {
        console.warn(err);
      } finally {
        this.loading = false;
      }
    },

    // 上传之前的校验
    beforeUpload(file) {
      console.log("🚀🚀 ~ beforeUpload ~ file:", file)
      
      const suffix = file.name.toLowerCase().split('.').splice(-1)[0];
      if (this.accept) {
        const isType = this.accept.search(suffix) === -1 ? false : true;
        if (!isType) {
          this.$message.warning('文件类型不正确！');

          this.isUpload = false;
          return false;
        }
      }
      if (file.size > 1024 * 1024 * this.maxSize) {
        this.$message.warning(`上传文件不能大于${this.maxSize}M！`);
        this.isUpload = false;
        return false;
      }
      this.isUpload = true;
      return true;
    },

    handleRemove(file, fileList) {
      const index = this.fileList.findIndex((item) => item.fileId === file.fileId);

      if (index !== -1) {
        this.fileList.splice(index, 1);
      }

      this.$emit('send-file-list', this.fileList);
    },

    beforeRemove(file, fileList) {
      if (!this.isUpload) {
        return;
      }
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    // 超出限制
    handleExceed(files, fileList) {
      if (this.limitText !== '') {
        this.$message.warning(this.limitText);
      } else {
        this.$message.warning(
          `当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
        );
      }
    },

    handleSuccess(res, file, fileList) {
      console.log('upload success', res, file, fileList);
    },

    clearFileList() {
      this.$refs['RefUploadFile'].clearFiles();
    },

    // ** ---------- 预览 ---------- **
    handlePreview(item) {
      // //获取文件格式
      // const index = item.name.lastIndexOf('.');
      // //获取文件后缀判断文件格式
      // const type = item.name.substr(index + 1).toLowerCase();
      // if (!['xlsx', 'pdf', 'docx', 'mp4', 'png', 'jpg', 'jpeg', 'gif'].includes(type)) {
      //   this.$confirm('该文件不支持预览,是否下载？', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   })
      //     .then(() => {
      //       // 用户点击了确定按钮，执行对应操作
      //       downloadFileByUrl(item.path || item.url, item.name);
      //     })
      //     .catch(() => {
      //       // 用户点击了取消按钮，取消对应操作
      //     });
      // } else {
      //   this.previewFile = item;
      //   this.dialogPreview = true;
      // }
    }
    // ** ---------- 预览  End---------- **
  }
};
</script>

<style lang="scss" scoped>
.preview-image {
  width: 100%;
}
.preview-file {
  height: 90vh;
  overflow: auto;
}

::v-deep .el-upload-dragger {
  width: 240px;
  height: 120px;
  .el-icon-upload {
    margin: 20px 0 8px;
  }
}
</style>
